import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:date_format/date_format.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get_rx/src/rx_workers/utils/debouncer.dart';
import 'package:intl/intl.dart';


import '../../AppConfig/Config.dart';
import '../../AppConfig/LocalStorage.dart';
import '../../AppConfig/RouteAct.dart';

import '../../Main/ProtocolDisplay.dart';
import '../../TabBar/TabbarView.dart';
import '../../http/api.dart';
import '../../l10n/messages.dart';
import 'ChooseCitySheet.dart';
import 'LoadingAddressView.dart';
import 'PaymentCycleSheet.dart';

class ModifyTransportationAgreement extends StatefulWidget {
  const ModifyTransportationAgreement({super.key, required this.dataMap,});
  final Map dataMap;
  @override
  State<ModifyTransportationAgreement> createState() => _ModifyTransportationAgreementState();
}

class _ModifyTransportationAgreementState extends State<ModifyTransportationAgreement> {
  TextEditingController _controller = TextEditingController();
  int isAgree=0;
  String startTimeDay="";
  String startTimeHour="";
  String startTimeCode="";
  String endTimeDay="";
  String endTimeHour="";
  String endTimeCode="";
  List carLength=[];
  List carType=[];
  String Weight="";
  String Velum="";
  String freight="";
  String startCitynameOne ="";
  List startCitycodeOne =[];
  String startCitynameTwo ="";
  List startCitycodeTwo =[];
  String endCitynameOne ="";
  List endCitycodeOne =[];
  String endCitynameTwo ="";
  List endCitycodeTwo =[];
  String selectedProvince = '';
  String selectedCity = '';
  String selectedDistrict = '';
  String selectedCityCode = '';
  List startAddressOne=[];
  List startAddressTwo=[];
  List endAddressOne=[];
  List endAddressTwo=[];
  List cityData = [];
  String detailAddressOne="";
  String detailAddressTwo="";
  String detailAddressThree="";
  String detailAddressFour="";
  Map startLocationOne={};
  Map startLocationTwo={};
  Map endLocationOne={};
  Map endLocationTwo={};
  bool isAddStart = false;
  bool isAddEnd = false;
  String dintanceStr="";
  String remark="";
  String carTypeStr="";
  String carLengthStr="";
  List beforeLoadAddress=[];
  List beforeUnloadAddress=[];
  List afterLoadAddress=[];
  List afterUnloadAddress=[];
  String dayStr="";
  int payPeriod=-1;
  String payTitle="";

  final Debouncer _debouncer = Debouncer(delay: Duration(seconds: 5));
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    freight =
        (widget.dataMap['contract']['contractInfo']['freight']).toString();
    remark =
    widget.dataMap['contract']['contractInfo']['remark'] != null ? (widget
        .dataMap['contract']['contractInfo']['remark']).toString() : "";
    _controller = TextEditingController(text: freight);
    startCitynameOne = widget
        .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][0]['province'] +
        widget
            .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][0]['city'] +
        widget
            .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][0]['county'];
    detailAddressOne = widget
        .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][0]['address'];
    startAddressOne = [
      widget
          .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][0]['province'],
      widget
          .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][0]['city'],
      widget
          .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][0]['county']
    ];
    if (widget.dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo']
        .length == 2) {
      startCitynameTwo = widget
          .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][1]['province'] +
          widget
              .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][1]['city'] +
          widget
              .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][1]['county'];
      detailAddressTwo = widget
          .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][1]['address'];
      startAddressTwo = [
        widget
            .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][1]['province'],
        widget
            .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][1]['city'],
        widget
            .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][1]['county']
      ];
    }
    endCitynameOne = widget
        .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][0]['province'] +
        widget
            .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][0]['city'] +
        widget
            .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][0]['county'];
    detailAddressThree = widget
        .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][0]['address'];
    endAddressOne = [
      widget
          .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][0]['province'],
      widget
          .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][0]['city'],
      widget
          .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][0]['county']
    ];
    if (widget
        .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo']
        .length == 2) {
      endCitynameTwo = widget
          .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][1]['province'] +
          widget
              .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][1]['city'] +
          widget
              .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][1]['county'];
      detailAddressFour = widget
          .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][1]['address'];
      endAddressTwo = [
        widget
            .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][1]['province'],
        widget
            .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][1]['city'],
        widget
            .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][1]['county']
      ];
    }
    endTimeDay =
    widget.dataMap['contract']['contractInfo']['goodsInfo']['unloadDay'];
    startTimeDay =
    widget.dataMap['contract']['contractInfo']['goodsInfo']['loadDay'];
    startTimeHour =
    widget.dataMap['contract']['contractInfo']['goodsInfo']['loadTime'];
    endTimeHour =
    widget.dataMap['contract']['contractInfo']['goodsInfo']['unloadTime'];
    carTypeStr =
    widget.dataMap['contract']['contractInfo']['vehicleInfo']['vehicleModel'];
    carLengthStr =
    widget.dataMap['contract']['contractInfo']['vehicleInfo']['vehicleLength'];
    Weight = widget
        .dataMap['contract']['contractInfo']['goodsInfo']['cargoInfo'][0]['cargoWeight']
        .toString();
    Velum = widget
        .dataMap['contract']['contractInfo']['goodsInfo']['cargoInfo'][0]['cargoVolume']
        .toString();
    beforeLoadAddress.add({
      "province": widget
          .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][0]['province'],
      "city": widget
          .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][0]['city'],
      "county": widget
          .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][0]['county'],
      "address": widget
          .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][0]['address'],
      "areaCode": widget
          .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][0]['areaCode'],
      "longitude": widget
          .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][0]['longitude'],
      "latitude": widget
          .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][0]['latitude']
    });
    if (widget.dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo']
        .length == 2)
      beforeLoadAddress.add({
        "province": widget
            .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][0]['province'],
        "city": widget
            .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][1]['city'],
        "county": widget
            .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][1]['county'],
        "address": widget
            .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][1]['address'],
        "areaCode": widget
            .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][1]['areaCode'],
        "longitude": widget
            .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][1]['longitude'],
        "latitude": widget
            .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][1]['latitude']
      });
    beforeUnloadAddress.add({
      "province": widget
          .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][0]['province'],
      "city": widget
          .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][0]['city'],
      "county": widget
          .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][0]['county'],
      "address": widget
          .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][0]['address'],
      "areaCode": widget
          .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][0]['areaCode'],
      "longitude": widget
          .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][0]['longitude'],
      "latitude": widget
          .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][0]['latitude']
    });
    if (widget
        .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo']
        .length == 2)
      beforeUnloadAddress.add({
        "province": widget
            .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][0]['province'],
        "city": widget
            .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][1]['city'],
        "county": widget
            .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][1]['county'],
        "address": widget
            .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][1]['address'],
        "areaCode": widget
            .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][1]['areaCode'],
        "longitude": widget
            .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][1]['longitude'],
        "latitude": widget
            .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][1]['latitude']
      });
    afterLoadAddress.addAll(beforeLoadAddress);
    afterUnloadAddress.addAll(beforeUnloadAddress);

    payPeriod=widget.dataMap['contract']['contractInfo']['payPeriod'];
    if (widget.dataMap['contract']['contractInfo']['payPeriod'] < 366)
      payTitle = "货到" +
          widget.dataMap['contract']['contractInfo']['payPeriod'].toString() +
          "天后付";
    if (widget.dataMap['contract']['contractInfo']['payPeriod'] == 801)
      payTitle = "货到付";
    if (widget.dataMap['contract']['contractInfo']['payPeriod'] == 802)
      payTitle = "回单付";
    if (widget.dataMap['contract']['contractInfo']['payPeriod'] == 830)
      payTitle = "月结";
    if (widget.dataMap['contract']['contractInfo']['payPeriod'] == 890)
      payTitle = "季结";
    if (widget.dataMap['contract']['contractInfo']['payPeriod'] == 980)
      payTitle = "季结";
  }
//获取距离
  Future<void> getDistanceAction() async {

    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.get<String>("https://api.map.baidu.com/directionlite/v1/driving?origin=${startLocationOne['lat']},${startLocationOne['lng']}&destination=${endLocationOne['lat']},${endLocationOne['lng']}&ak=0t6rhRWUGmqtbsMRMBVSqzbBwBrCzXLj")
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(r.toString());
        // 获取code和data
        String code = jsonMap['status'].toString();
        if (code == "0") {
          setState(() {
            List list =jsonMap['result']['routes'];
            dintanceStr = list[0]['distance'].toString();
          });
        } else {

        }
        // 打印结果
        print('Code: $code');
      });
    }).catchError((error) {
      print(error);
    });

  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        backgroundColor: Colors.white,
        leading: IconButton(
          onPressed: () {
            Navigator.pop(context);
          },
          icon: Icon(Icons.arrow_back_ios),
        ),
        centerTitle: true,
        title: Text("修改货物运输协议",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w300,fontSize: 16.sp),),
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView(
              children: [
                if(widget.dataMap['deposit']!=0)
                  Container(
                    margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
                    padding: EdgeInsets.only(left: 12.w,top: 16.h,right: 9.w,bottom: 5.h),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(10)),
                    ),
                    child: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                Text("订金",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                                Container(
                                  // width: 36.w,
                                  height: 15.h,
                                  padding: EdgeInsets.only(left:4.w,right:4.w),
                                  decoration: BoxDecoration(
                                    gradient: LinearGradient(
                                      begin: Alignment.topCenter,
                                      end: Alignment.bottomCenter,
                                      colors: [Color.fromRGBO(236,111,66,1), Color.fromRGBO(239,160,82,1)],
                                    ),
                                    borderRadius: BorderRadius.circular(3.0),
                                  ),
                                  child: Center(
                                    child: Text(widget.dataMap['contract']['contractInfo']['depositType']==0?'退还':"不退还", style: TextStyle(color: Colors.white, fontSize: 12.0, fontWeight: FontWeight.w600
                                    ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            Text((widget.dataMap['contract']['contractInfo']['depositType']==-1?"0元":(widget.dataMap['contract']['contractInfo']['deposit']).toString()+"元"),style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                          ],
                        ),
                        SizedBox(height: 4.h,),
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Icon(Icons.error,color: Color.fromRGBO(206, 206, 206, 1),size: 17,),

                            Container(
                              width: screenSize.width-70.w,
                              child: Text("订金担保：订金支付到平台用于订货押金，货主收货后，将退还给您。",style: TextStyle(color: MyColors.authTipColor,fontSize: 11.sp),softWrap: true,),
                            ),
                          ],
                        )
                      ],
                    ),
                  ),
                Container(
                  margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
                  padding: EdgeInsets.only(left: 10.w,top: 10.h,right: 10.w,bottom: 10.h),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10)),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text("运费",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                          Container(
                            width: 130.w,
                            height: 33.h,
                            color: Color.fromRGBO(248, 248, 248, 1),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Container(
                                  margin: EdgeInsets.only(left: 8.w),
                                  width: 100.w,
                                  height: 20.h,
                                  color: MyColors.backgreyColor,
                                  child:  TextField(
                                    controller: _controller,
                                    decoration: InputDecoration(
                                      hintText: "输入运费",
                                      hintStyle:TextStyle(fontSize: 13.sp,color: Colors.black),
                                      filled: true,
                                      fillColor: MyColors.backgreyColor,
                                      border: InputBorder.none,
                                      alignLabelWithHint: true,
                                      contentPadding: EdgeInsets.symmetric(vertical: 6.0.h, horizontal: 0.0.w),
                                    ),
                                    keyboardType: TextInputType.number,
                                    textAlign: TextAlign.left,
                                    style: TextStyle(color: Colors.black,fontSize: 14.sp),
                                    onChanged: (value) {
                                      setState(() {
                                        freight=value;
                                      });
                                    },
                                  ),
                                ),
                                Text("元",style: TextStyle(color: Colors.black),)
                              ],
                            ),
                          ),
                        ],
                      ),
                      // Divider(height: 16.h,color: MyColors.backgreyColor,),
                      // Text("服务费",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                      // SizedBox(height: 8.h,),
                      // Row(
                      //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      //   children: [
                      //     Text("电子协议费",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                      //     Text((widget.dataMap['elecProtocolCharge']).toString()+"元",style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                      //   ],
                      // ),
                      // SizedBox(height: 8.h,),
                      // Row(
                      //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      //   children: [
                      //     Text("轨迹校验费",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                      //     Text((widget.dataMap['trajectoryVerificationCharge']).toString()+"元",style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                      //   ],
                      // ),
                      // SizedBox(height: 8.h,),
                      // Row(
                      //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      //   children: [
                      //     Text("技术服务费",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                      //     Text((widget.dataMap['techServiceCharge']).toString()+"元",style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                      //   ],
                      // ),
                      // SizedBox(height: 14.h,),
                      // Row(
                      //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      //   children: [
                      //     Row(
                      //       children: [
                      //         Text("总费用",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w600),),
                      //         Text("（不包含订金）",style: TextStyle(color: MyColors.authTipColor),),
                      //       ],
                      //     ),
                      //     Text((widget.dataMap['alreadyAmount']).toString()+"元",style: TextStyle(color: MyColors.themeColor),),
                      //   ],
                      // ),
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
                  padding: EdgeInsets.only(left: 15.w,top: 11.h,bottom: 17.h),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10)),
                  ),
                  child: Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          SizedBox(),
                          GestureDetector(
                            child: Column(
                              children: [
                                Text("装货",style: TextStyle(color:Color.fromRGBO(102, 102, 102, 1),fontSize: 12.sp ),),
                                SizedBox(height: 4.h,),
                                Text(startTimeDay!=""?startTimeDay:widget.dataMap['contract']['contractInfo']['goodsInfo']['loadDay'],style: TextStyle(color:Color.fromRGBO(51, 51, 51, 1),fontSize: 12.sp ),),
                                SizedBox(height: 4.h,),
                                Text(startTimeHour.contains(":")?startTimeHour:(widget.dataMap['contract']['contractInfo']['goodsInfo']['loadTime']+"点装货"),style: TextStyle(color:Colors.black,fontSize: 12.sp ),),
                              ],
                            ),
                            onTap: () async {
                              final result = await  showModalBottomSheet(context: context,
                                  isScrollControlled:true,
                                  isDismissible: false, // 设置为 false，点击外部区域不关闭
                                  enableDrag: false, // 设置为 false，禁用上滑手势关闭
                                  builder: (BuildContext context)
                                  {
                                    return  ChooseTimeSheet(chooseTimeType: 1,);
                                  });
                              if (result != null) {
                                setState(() {
                                  startTimeDay = result[0];
                                  startTimeHour = result[1];
                                  startTimeCode =result[2];
                                });
                              }
                            },
                          ),
                          Row(
                            children: [
                              Icon(Icons.circle,color:Color.fromRGBO(251, 236, 228, 1) ,size:8,),
                              SizedBox(width: 6.w,),
                              Icon(Icons.circle,color:Color.fromRGBO(255, 179, 115, 1) ,size:8,),
                              SizedBox(width: 6.w,),
                              Icon(Icons.circle,color:Color.fromRGBO(240, 133, 44, 1) ,size:8,),
                              SizedBox(width: 6.w,),
                              Image.asset("lib/Images/OrderList/司机简介车辆信息icon.png",width: 24.w,height: 24.h,),
                              SizedBox(width: 6.w,),
                              Icon(Icons.circle,color:Color.fromRGBO(240, 133, 44, 1) ,size:8,),
                              SizedBox(width: 6.w,),
                              Icon(Icons.circle,color:Color.fromRGBO(255, 179, 115, 1) ,size:8,),
                              SizedBox(width: 6.w,),
                              Icon(Icons.circle,color:Color.fromRGBO(251, 236, 228, 1) ,size:8,),
                            ],
                          ),
                          GestureDetector(
                            child: Column(
                              children: [
                                Text("卸货",style: TextStyle(color:Color.fromRGBO(102, 102, 102, 1),fontSize: 12.sp ),),
                                SizedBox(height: 4.h,),
                                widget.dataMap['contract']['contractInfo']['goodsInfo']['unloadTime']!=null?
                                Text(endTimeDay!=""?endTimeDay:widget.dataMap['contract']['contractInfo']['goodsInfo']['unloadDay'],style: TextStyle(color:Color.fromRGBO(51, 51, 51, 1),fontSize: 12.sp ),)
                                    :Text(endTimeDay!=""?endTimeDay:"--",style: TextStyle(color:Color.fromRGBO(51, 51, 51, 1),fontSize: 12.sp ),),
                                SizedBox(height: 4.h,),
                                widget.dataMap['contract']['contractInfo']['goodsInfo']['unloadTime']!=null?
                                Text(endTimeHour.contains(":")?endTimeHour:(widget.dataMap['contract']['contractInfo']['goodsInfo']['unloadTime']+"点卸货"),style: TextStyle(color:Colors.black,fontSize: 12.sp ),):

                                Text(endTimeHour!=""?endTimeHour:"选择卸货时间>",style: TextStyle(color:Colors.black,fontSize: 12.sp ),),
                              ],
                            ),
                            onTap: () async {
                              final result = await  showModalBottomSheet(context: context,
                                  isScrollControlled:true,
                                  isDismissible: false, // 设置为 false，点击外部区域不关闭
                                  enableDrag: false, // 设置为 false，禁用上滑手势关闭
                                  builder: (BuildContext context)
                                  {
                                    return  ChooseTimeSheet(chooseTimeType: 2,);
                                  });
                              if (result != null) {
                                setState(() {
                                  endTimeDay = result[0];
                                  endTimeHour = result[1];
                                  endTimeCode =result[2];
                                });
                              }
                            },
                          ),
                          SizedBox(),
                        ],
                      ),
                      SizedBox(height: 16.h,),
                      Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [

                              Row(
                                children: [
                                  Image.asset("lib/Images/OrderList/装货点icon.png",width: 20.w,height: 20.h,),
                                  Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Container(
                                        width:screenSize.width-120.w,
                                        padding: EdgeInsets.only(left: 10.w),
                                        child:   GestureDetector(
                                          child:Text(startCitynameOne!=""?startCitynameOne: "必填，请选择装货省市区",style: TextStyle(color:startCitynameOne!=""?Colors.black: MyColors.textColor,fontSize: 14.sp),),
                                          onTap: ()async{
                                            final result = await  showModalBottomSheet(context: context,
                                                isScrollControlled:true,
                                                isDismissible: false, // 设置为 false，点击外部区域不关闭
                                                enableDrag: false, // 设置为 false，禁用上滑手势关闭
                                                builder: (BuildContext context)
                                                {

                                                  return chooseCitySheet(chooseType: 1,cityData: cityData, chooseCityList: startAddressOne,chooseCodeList: startCitycodeOne,);
                                                });
                                            if (result != null) {
                                              setState(() {
                                                print(result);
                                                startCitynameOne = result[0]+" "+result[1]+" "+result[2];
                                                startCitycodeOne =[result[3],result[4],result[5]];
                                                startAddressOne=[result[0],result[1],result[2]];
                                              });
                                            }
                                          },
                                        ),

                                      ),

                                      Divider(height: 5.h,color: Colors.black,),
                                      Container( 
                                        width:screenSize.width-120.w,
                                        padding: EdgeInsets.only(left: 10.w),
                                        child:   GestureDetector(
                                          child:Text(detailAddressOne!=""?detailAddressOne:"必填，请填写详细地址",overflow: TextOverflow.clip,style: TextStyle(color: detailAddressOne!=""?MyColors.textColor:MyColors.hintColor,fontSize: 13.sp),), 
                                          onTap: ()async{
                                            final result = await  Navigator.push( context, FadeRoute(page:LoadingAddressView(addressType: 1, region: startAddressOne.isNotEmpty?startAddressOne[1]:"",)));
                                            if(result!=null){
                                              setState(() {
                                                print(result);
                                                startCitynameOne=result['province']+" "+result['city']+" "+result['district'];
                                                startCitycodeOne=[result['adcode'].substring(0, 2)+"0000",result['adcode'].substring(0, 4)+"00",result['adcode']];
                                                startAddressOne=[result['province'],result['city'],result['district']];
                                                detailAddressOne=result['address'];
                                                startLocationOne=result['location'];
                                                print(startCitycodeOne);
                                                if(detailAddressOne!=""&&detailAddressThree!=""){
                                                  getDistanceAction();
                                                }
                                              });

                                            }
                                          },
                                        ),

                                      ),


                                    ],
                                  )
                                ],
                              ),
                              // isAddStart ==false?
                              // IconButton(onPressed: (){
                              //   setState(() {
                              //     isAddStart=true;
                              //   });
                              // }, icon: Icon(Icons.add_circle_outline,color: MyColors.textColor,))
                              //     :SizedBox(width: 10.w,),
                            ],
                          ),
                          Divider(height: 20.h,color: MyColors.backgreyColor,),
                          if(widget.dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'].length==2)
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    Image.asset("lib/Images/OrderList/装货点icon.png",width: 20.w,height: 10.h,),
                                    Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Container(
                                          width:screenSize.width-120.w,
                                          padding: EdgeInsets.only(left: 10.w),
                                          child:   GestureDetector(
                                            child:Text(startCitynameTwo!=""?startCitynameTwo: "必填，请选择装货省市区",style: TextStyle(color:startCitynameTwo!=""?Colors.black: MyColors.textColor,fontSize: 14.sp),),
                                            onTap: ()async{
                                              final result = await  showModalBottomSheet(context: context,
                                                  isScrollControlled:true,
                                                  isDismissible: false, // 设置为 false，点击外部区域不关闭
                                                  enableDrag: false, // 设置为 false，禁用上滑手势关闭
                                                  builder: (BuildContext context)
                                                  {
                                                    return chooseCitySheet(chooseType: 2,cityData: cityData,chooseCityList: startAddressTwo,chooseCodeList: startCitycodeTwo,);
                                                  });
                                              if (result != null) {
                                                setState(() {
                                                  startCitynameTwo= result[0]+" "+result[1]+" "+result[2];
                                                  startCitycodeTwo =[result[3],result[4],result[5]];
                                                  startAddressTwo=[result[0],result[1],result[2]];
                                                });
                                              }
                                            },
                                          ),
                                        ),
                                        Divider(height: 10.h,color: MyColors.backgreyColor,),
                                        Container(
                                          width:screenSize.width-120.w,
                                          padding: EdgeInsets.only(left: 10.w),
                                          child:   GestureDetector(
                                            child:Text(detailAddressTwo!=""?detailAddressTwo:"必填，请填写详细地址",overflow: TextOverflow.clip,style: TextStyle(color: detailAddressTwo!=""?MyColors.textColor:MyColors.hintColor,fontSize: 13.sp),),
                                            onTap: ()async{
                                              final result = await  Navigator.push( context, FadeRoute(page:LoadingAddressView(addressType: 2, region:startAddressTwo.isNotEmpty?startAddressTwo[1]:"",)));
                                              if(result!=null){
                                                setState(() {
                                                  startCitynameTwo=result['province']+" "+result['city']+" "+result['district'];
                                                  startCitycodeTwo=[result['adcode'].substring(0, 2)+"0000",result['adcode'].substring(0, 4)+"00",result['adcode']];
                                                  startAddressTwo=[result['province'],result['city'],result['district']];
                                                  detailAddressTwo=result['address'];
                                                  startLocationTwo=result['location'];
                                                });

                                              }
                                            },
                                          ),

                                        ),

                                      ],
                                    )

                                  ],
                                ),

                                // IconButton(onPressed: (){
                                //   setState(() {
                                //     isAddStart=false;
                                //   });
                                // }, icon: Icon(Icons.remove_circle_outline,color: MyColors.textColor,)),
                              ],
                            ),
                          if (widget
                              .dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'].length==2)
                            Divider(height: 20.h,color: MyColors.backgreyColor,),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  Image.asset("lib/Images/OrderList/卸货点icon.png",width: 20.w,height: 20.h,),

                                  Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Container(
                                        width:screenSize.width-120.w,
                                        padding: EdgeInsets.only(left: 10.w),
                                        child:   GestureDetector(
                                          child:Text(endCitynameOne!=""?endCitynameOne: "必填，请选择卸货省市区",style: TextStyle(color:endCitynameOne!=""?Colors.black: MyColors.textColor,fontSize: 14.sp),),
                                          onTap: ()async{
                                            final result = await  showModalBottomSheet(context: context,
                                                isScrollControlled:true,
                                                isDismissible: false, // 设置为 false，点击外部区域不关闭
                                                enableDrag: false, // 设置为 false，禁用上滑手势关闭
                                                builder: (BuildContext context)
                                                {
                                                  return chooseCitySheet(chooseType: 3,cityData: cityData,chooseCityList: endAddressOne,chooseCodeList: endCitycodeOne,);
                                                });
                                            if (result != null) {
                                              setState(() {
                                                endCitynameOne = result[0]+" "+result[1]+" "+result[2];
                                                endCitycodeOne =[result[3],result[4],result[5]];
                                                endAddressOne=[result[0],result[1],result[2]];
                                              });
                                            }
                                          },
                                        ),

                                      ),

                                      Divider(height: 5.h,color: MyColors.backgreyColor,),

                                      Container(
                                        width:screenSize.width-120.w,
                                        padding: EdgeInsets.only(left: 10.w),
                                        child:   GestureDetector(
                                          child:Text(detailAddressThree!=""?detailAddressThree:"必填，请填写详细地址",overflow: TextOverflow.clip,style: TextStyle(color: detailAddressThree!=""?MyColors.textColor:MyColors.hintColor,fontSize: 13.sp),),
                                          onTap: ()async{
                                            final result = await  Navigator.push( context, FadeRoute(page:LoadingAddressView(addressType: 2, region: endAddressOne.isNotEmpty?endAddressOne[1]:"",)));
                                            if(result!=null){
                                              setState(() {
                                                endCitynameOne=result['province']+" "+result['city']+" "+result['district'];
                                                endCitycodeOne=[result['adcode'].substring(0, 2)+"0000",result['adcode'].substring(0, 4)+"00",result['adcode']];
                                                endAddressOne=[result['province'],result['city'],result['district']];
                                                detailAddressThree=result['address'];
                                                endLocationOne=result['location'];
                                                if(detailAddressOne!=""&&detailAddressThree!=""){
                                                  getDistanceAction();
                                                }
                                              });

                                            }
                                          },
                                        ),

                                      ),

                                      // ),
                                    ],
                                  ),
                                ],
                              ),
                              // isAddEnd==false?
                              // IconButton(onPressed: (){
                              //   setState(() {
                              //     isAddEnd=true;
                              //   });
                              // }, icon: Icon(Icons.add_circle_outline,color: MyColors.textColor,))
                              //     :SizedBox(width: 10.w,),
                            ],
                          ),
                          if (widget
                              .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'].length==2)
                            Divider(height: 20.h,color: MyColors.backgreyColor,),
                          if (widget
                              .dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'].length==2)
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    Image.asset("lib/Images/OrderList/卸货点icon.png",width:20.w,height: 10.h,),
                                    Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      mainAxisAlignment: MainAxisAlignment.start,
                                      children: [
                                        Container(
                                          width:screenSize.width-120.w,
                                          padding: EdgeInsets.only(left: 10.w),
                                          child:   GestureDetector(
                                            child:Text(endCitynameTwo!=""?endCitynameTwo: "必填，请选择卸货省市区",style: TextStyle(color:endCitynameTwo!=""?MyColors.textColor: MyColors.textColor,fontSize: 13.sp),),
                                            onTap: ()async{
                                              final result = await  showModalBottomSheet(context: context,
                                                  isScrollControlled:true,
                                                  isDismissible: false, // 设置为 false，点击外部区域不关闭
                                                  enableDrag: false, // 设置为 false，禁用上滑手势关闭
                                                  builder: (BuildContext context)
                                                  {
                                                    return chooseCitySheet(chooseType: 4,cityData: cityData,chooseCityList: endAddressTwo, chooseCodeList: endCitycodeTwo,);
                                                  });
                                              if (result != null) {
                                                setState(() {
                                                  endCitynameTwo = result[0]+" "+result[1]+" "+result[2];
                                                  endCitycodeTwo =[result[3],result[4],result[5]];
                                                  endAddressTwo=[result[0],result[1],result[2]];
                                                });
                                              }
                                            },
                                          ),

                                        ),

                                        Divider(height: 5.h,color: MyColors.backgreyColor,),
                                        Container(
                                          width:screenSize.width-120.w,
                                          padding: EdgeInsets.only(left: 10.w),
                                          child:   GestureDetector(
                                            child:Text(detailAddressFour!=""?detailAddressFour:"必填，请填写详细地址",overflow: TextOverflow.clip,style: TextStyle(color: detailAddressFour!=""?Colors.black:MyColors.hintColor,fontSize: 14.sp),),
                                            onTap: ()async{
                                              final result = await  Navigator.push( context, FadeRoute(page:LoadingAddressView(addressType: 2, region: endAddressTwo.isNotEmpty?endAddressTwo[1]:"",)));
                                              if(result!=null){
                                                setState(() {
                                                  endCitynameTwo=result['province']+" "+result['city']+" "+result['district'];
                                                  endAddressTwo=[result['province'],result['city'],result['district']];
                                                  detailAddressFour=result['address'];
                                                  endLocationTwo=result['location'];
                                                });

                                              }
                                            },
                                          ),

                                        ),
                                      ],
                                    )
                                  ],
                                ),
                                //
                                // IconButton(onPressed: (){
                                //   setState(() {
                                //     isAddEnd=false;
                                //   });
                                // }, icon: Icon(Icons.remove_circle_outline,color: MyColors.textColor,)),
                              ],
                            ),
                        ],
                      ),

                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
                  padding: EdgeInsets.only(left: 15.w,top: 18.h,right: 16.w,bottom: 10.h),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10)),
                  ),
                  child: Column(
                    children: [
                      GestureDetector(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text("付款时间",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                            // if(payPeriod==-1&&dayStr=="")
                            //   Text("请选择周期",style:TextStyle(color:MyColors.hintColor,fontSize: 14.sp )),
                            // if(dayStr!="")
                            //   Text("货到"+dayStr+"天后付",style:TextStyle(color:Colors.black,fontSize: 14.sp )),
                            // if(payPeriod!=-1)
                              Text(payTitle,style:TextStyle(color:Colors.black,fontSize: 13.sp )),
                          ],
                        ),
                        onTap:()async{
                          final result=await showModalBottomSheet(context: context, builder: (BuildContext context) {
                            return PaymentCycleSheet(payPeriod: payPeriod, payPeriodStr:payTitle, dayStr: dayStr,
                            );});
                          if(result!=null){
                            setState(() {
                              payPeriod=result[0];
                              dayStr=result[1];
                              payTitle=result[2];
                              if(payPeriod<366){
                                payTitle = "货到" +
                                    widget.dataMap['contract']['contractInfo']['payPeriod'].toString() +
                                    "天后付";
                              }
                            });

                          }
                        },
                      ),

                      Divider(height: 30.h,color: MyColors.backgreyColor,),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text("货物名称",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                          Text(widget.dataMap['contract']['contractInfo']['goodsInfo']['cargoInfo'][0]['cargoName'],style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                        ],
                      ),
                      Divider(height: 30.h,color: MyColors.backgreyColor,),
                      GestureDetector(
                        child:   Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text("车型车长",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                            Row(
                              children: [ !carLength.isEmpty&&!carType.isEmpty?
                              Text(carLength.map((element) => '$element米').join(', ')+"\n"+carType.join(', '),style: TextStyle(color: Colors.black,fontSize: 14.sp),):
                              Text(widget.dataMap['contract']['contractInfo']['vehicleInfo']['vehicleLength'].replaceAll(',', '米')+"/"+widget.dataMap['contract']['contractInfo']['vehicleInfo']['vehicleModel'] ,style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                                Icon(Icons.arrow_forward_ios,color: MyColors.hintColor,size: 16,),

                              ],
                            ),
                          ],
                        ),
                        onTap: () async {
                          final result = await  showModalBottomSheet(context: context,
                              isScrollControlled:true,
                              isDismissible: false, // 设置为 false，点击外部区域不关闭
                              enableDrag: false, // 设置为 false，禁用上滑手势关闭
                              builder: (BuildContext context)
                              {
                                return  carLengthandTypeSheet(carLength: carLength, carType: carType,);
                              });
                          if (result != null) {
                            setState(() {
                              carLength = result[0];
                              carLengthStr=carLength.map((element) => '$element').join(', ');
                              carType=result[1];
                              carTypeStr=carType.join(', ');
                            });
                          }

                        },
                      ),
                      Divider(height: 30.h,color: MyColors.backgreyColor,),
                      GestureDetector(
                        child:   Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text("重量/体积",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                            Row(
                              children: [
                                if(widget.dataMap['contract']['contractInfo']['goodsInfo']['cargoInfo'][0]['cargoWeight']!=null&&Weight==""&&Velum=="")
                                  Text(widget.dataMap['contract']['contractInfo']['goodsInfo']['cargoInfo'][0]['cargoWeight'].toString()+"吨",style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                                if(Weight!="")
                                  Text(Weight+"吨",style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                                if(widget.dataMap['contract']['contractInfo']['goodsInfo']['cargoInfo'][0]['cargoVolume']!=null&&Velum==""&&Weight=="")
                                  Text(widget.dataMap['contract']['contractInfo']['goodsInfo']['cargoInfo'][0]['cargoVolume'].toString()+"方",style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                                if(Velum!="")
                                  Text(Velum+"方",style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                                Icon(Icons.arrow_forward_ios,color: MyColors.hintColor,size: 16,),
                              ],
                            ),
                          ],
                        ),
                        onTap: () async {
                          final result = await  showModalBottomSheet(context: context,
                              isScrollControlled:true,
                              isDismissible: false, // 设置为 false，点击外部区域不关闭
                              enableDrag: false, // 设置为 false，禁用上滑手势关闭
                              builder: (BuildContext context)
                              {
                                return  WeightVelumSheet(weight: Weight, velum: Velum,);
                              });
                          if (result != null) {
                            setState(() {
                              Weight = result[0];
                              Velum=result[1];
                            });
                          }

                        },
                      ),
                      Divider(height: 30.h,color: MyColors.backgreyColor,),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text("承运车牌",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                          Text(widget.dataMap['contract']['contractInfo']['vehicleInfo']['vehicleNum'],style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                        ],
                      ),
                      Divider(height: 30.h,color: MyColors.backgreyColor,),
                      Row(
                        children: [
                          Icon(Icons.error,color: MyColors.hintColor,size: 18,),
                          SizedBox(width: 4.w,),
                          Text("确保车辆与承运车辆一致，否则保障无效",style: TextStyle(fontSize: 10.sp,color:MyColors.authTipColor ),)
                        ],
                      ),
                      Divider(height: 16.h,color: MyColors.backgreyColor,),
                      Row(
                        children: [
                          Text("补充约定",style: TextStyle(color:MyColors.textColor,fontSize: 13.sp),),
                        ],
                      ),
                      Container(
                        child: BrnInputText(
                          autoFocus: false,
                          maxHeight: 200,
                          minHeight: 30,
                          minLines: 1,
                          maxLength: 140,
                          bgColor: MyColors.backgreyColor,
                          textInputAction: TextInputAction.newline,
                          textString:remark ?? '',
                          maxHintLines: 20,
                          hint: '请输入您要补充的内容',
                          padding: EdgeInsets.fromLTRB(20, 10, 20, 14),
                          onTextChange: (text) {
                            setState(() {
                              remark=text;
                            });
                          },
                          onSubmit: (text) {
                            print(text);
                          },
                        ),
                      ),

                    ],
                  ),
                ),

              ],
            ),
          ),
          Container(
            height: 110.h,
            color: Colors.white,
            padding: EdgeInsets.only(left: 15.w,right: 15.w,top:10.h,bottom: 20.h ),
            child: Column(
              children: [
                Container(
                  margin: EdgeInsets.only(left: 12.w,top: 8.h),
                  child: Row(
                    children: [
                      GestureDetector(
                        child: Icon(isAgree==1?Icons.radio_button_checked :Icons.circle_outlined,color:isAgree==1?MyColors.themeColor: MyColors.authTipColor,),
                        onTap: (){
                          setState(() {
                            isAgree==1?isAgree=0:isAgree=1;
                          });
                        },
                      ),
                      SizedBox(width: 4.w,),
                      Text("我已阅读并同意",style: TextStyle(color: Colors.black,fontSize: 12.sp),),
                      GestureDetector(
                        child: Text("《货物运输协议》",style: TextStyle(color: MyColors.blueColor,fontSize: 12.sp),),
                        onTap: (){
                          Navigator.push( context, FadeRoute(page:ProtocolDisplay(id: "1805851815423774721",)));
                        },
                      ),
                    ],
                  ),
                ),
                SizedBox(height: 8.h,),
                BrnSmallMainButton(
                  title: '提交',
                  bgColor:MyColors.themeColor,
                  radius: 30,
                  fontSize: 16.sp,
                  width: screenSize.width-30.w,
                  onTap: ()async {
                    if (isAgree==0){
                      BrnToast.show("请同意货物运输协议", context);
                    }else {
                      _debouncer(() {
                        Map updateInfo={};
                        if(freight!=widget.dataMap['contract']['contractInfo']['freight'].toString()){
                          updateInfo['freight']={
                            "after": freight,
                            "before": widget.dataMap['contract']['contractInfo']['freight']
                          };
                        }
                        if(Weight!=widget.dataMap['contract']['contractInfo']['goodsInfo']['cargoInfo'][0]['cargoWeight'].toString()||Velum!=widget.dataMap['contract']['contractInfo']['goodsInfo']['cargoInfo'][0]['cargoVolume'].toString()){
                          updateInfo['cargo']={
                            "after": [{"cargoWeight":Weight,"cargoVolume":Velum,
                              "cargoName":widget.dataMap['contract']['contractInfo']['goodsInfo']['cargoInfo'][0]['cargoName'],
                              "packageType":widget.dataMap['contract']['contractInfo']['goodsInfo']['cargoInfo'][0]['packageType'],
                              "cargoTypeCode":widget.dataMap['contract']['contractInfo']['goodsInfo']['cargoInfo'][0]['cargoTypeCode']}],
                            "before":[{"cargoWeight":widget.dataMap['contract']['contractInfo']['goodsInfo']['cargoInfo'][0]['cargoWeight'].toString(),
                              "cargoVolume":widget.dataMap['contract']['contractInfo']['goodsInfo']['cargoInfo'][0]['cargoVolume'].toString(),
                              "cargoName":widget.dataMap['contract']['contractInfo']['goodsInfo']['cargoInfo'][0]['cargoName'],
                              "packageType":widget.dataMap['contract']['contractInfo']['goodsInfo']['cargoInfo'][0]['packageType'],
                              "cargoTypeCode":widget.dataMap['contract']['contractInfo']['goodsInfo']['cargoInfo'][0]['cargoTypeCode']
                            }],
                          };
                        }
                        if(carLengthStr!=widget.dataMap['contract']['contractInfo']['vehicleInfo']['vehicleLength'].toString()){
                          updateInfo['vehicleLength']={
                            "after": carLengthStr,
                            "before":widget.dataMap['contract']['contractInfo']['vehicleInfo']['vehicleLength'],
                          };
                        }
                        if(carTypeStr!=widget.dataMap['contract']['contractInfo']['vehicleInfo']['vehicleModel'].toString()){
                          updateInfo['vehicleModel']={
                            "after": carTypeStr,
                            "before":widget.dataMap['contract']['contractInfo']['vehicleInfo']['vehicleModel'],
                          };
                        }
                        if(remark!=""&&remark!=widget.dataMap['contract']['contractInfo']['remark'].toString()){
                          updateInfo['remark']={
                            "after": remark,
                            "before":widget.dataMap['contract']['contractInfo']['remark'].toString(),
                          };
                        }
                        if(startTimeDay!=widget.dataMap['contract']['contractInfo']['goodsInfo']['loadDay'].toString()){
                          updateInfo['loadTime']={
                            "after":{"day":startTimeDay,"time":startTimeHour} ,
                            "before":{"day":widget.dataMap['contract']['contractInfo']['goodsInfo']['loadDay'],"time":widget.dataMap['contract']['contractInfo']['goodsInfo']['loadTime']} ,
                          };
                        }
                        if(endTimeDay!=widget.dataMap['contract']['contractInfo']['goodsInfo']['unloadDay'].toString()){
                          updateInfo['loadTime']={
                            "after":{"day":endTimeDay,"time":endTimeHour} ,
                            "before":{"day":widget.dataMap['contract']['contractInfo']['goodsInfo']['unloadDay'],"time":widget.dataMap['contract']['contractInfo']['goodsInfo']['unloadTime']} ,
                          };
                        }
                        if(payPeriod!=widget.dataMap['contract']['contractInfo']['payPeriod']){
                          updateInfo['payPeriod']={
                            "after":payPeriod ,
                            "before": widget.dataMap['contract']['contractInfo']['payPeriod'],
                          };
                        }
                        if(detailAddressOne!=widget.dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][0]['address'].toString()){
                          afterLoadAddress[0]={"province":startAddressOne[0],
                            "city":startAddressOne[1],
                            "county":startAddressOne[2],
                            "address":detailAddressOne,
                            "areaCode":startCitycodeOne[2],
                            "longitude":startLocationOne['lng'],
                            "latitude":startLocationOne['lat']};
                          updateInfo['loadPlace'] = {
                            "after": afterLoadAddress,
                            "before": beforeLoadAddress,
                          };

                        }
                        if(widget.dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'].length==2&&detailAddressTwo!=widget.dataMap['contract']['contractInfo']['goodsInfo']['loadPlaceInfo'][1]['address'].toString()){
                          afterLoadAddress[1]={"province":startAddressTwo[0],
                            "city":startAddressTwo[1],
                            "county":startAddressTwo[2],
                            "address":detailAddressTwo,
                            "areaCode":startCitycodeTwo[2],
                            "longitude":startLocationTwo['lng'],
                            "latitude":startLocationTwo['lat']};
                          updateInfo['loadPlace'] = {
                            "after": afterLoadAddress,
                            "before": beforeLoadAddress,
                          };

                        }

                        if(detailAddressThree!=widget.dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][0]['address'].toString()){

                          afterUnloadAddress[0]={"province":endAddressOne[0],
                            "city":endAddressOne[1],
                            "county":endAddressOne[2],
                            "address":detailAddressThree,
                            "areaCode":endCitycodeOne[2],
                            "longitude":endLocationOne['lng'],
                            "latitude":endLocationOne['lat']};

                          updateInfo['unloadPlace'] = {
                            "after": afterUnloadAddress,
                            "before": beforeUnloadAddress,
                          };
                        }
                        if(widget.dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'].length==2&&detailAddressFour!=widget.dataMap['contract']['contractInfo']['goodsInfo']['unloadPlaceInfo'][0]['address'].toString()){
                          afterUnloadAddress[1]={"province":endAddressTwo[0],
                            "city":endAddressTwo[1],
                            "county":endAddressTwo[2],
                            "address":detailAddressFour,
                            "areaCode":endCitycodeTwo[2],
                            "longitude":endLocationTwo['lng'],
                            "latitude":endLocationTwo['lat']};

                          updateInfo['unloadPlace'] = {
                            "after": afterUnloadAddress,
                            "before": beforeUnloadAddress,
                          };
                        }



                        ApiManager.postData(
                          context,
                          'api/waybill/contract/rebuild',
                          {
                            "beforeContractId":widget.dataMap['contract']['id'],
                            "updateInfo":updateInfo,

                          },
                              (responseData) {
                            setState(() {
                              BrnToast.show(
                                "修改成功",
                                context,
                                duration: BrnDuration.short,
                              );
                              Navigator.pushReplacement(
                                context,
                                MaterialPageRoute(builder: (context) => TabbarView(pateIndex: 2,),fullscreenDialog: true,),
                              );
                            });
                          },
                        );
                      });
                    }
                  },
                ),
              ],
            ),

          ),
        ],
      ),
    );
  }
}
class ChooseTimeSheet extends StatefulWidget {
  const ChooseTimeSheet({super.key, required this.chooseTimeType});
  final int chooseTimeType;
  @override
  State<ChooseTimeSheet> createState() => _ChooseTimeSheetState();
}

class _ChooseTimeSheetState extends State<ChooseTimeSheet> {
  String startTimeDay="";
  String startTimeHour="";
  String startTimeCode="";
  List chooseTimeList=["全天都可以","凌晨 00:00-6:00","上午 06:00-12:00","下午 12:00-18:00","晚上 18:00-24:00"
    ,"00:00-02:00","02:00-:04:00","04:00-06:00","06:00-08:00","08:00-10:00","10:00-12:00","12:00-14:00",
    "14:00-16:00","16:00-18:00","18:00-20:00","20:00-22:00","22:00-24:00"];
  List timeCodeList=["0-24","0-6","6-12","12-18","18-24","0-2","2-4","4-6","6-8","8-10","10-12","12-14","14-16","16-18","18-20","20-22","22-24"];
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    List<String> dateList = generateDateList();
    return Container(
      height:300.h,
      padding: EdgeInsets.only(top: 10.h,bottom: 44.h,left: 15.w,right: 15.w),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(10))),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              GestureDetector(
                child: Row(
                    children:[
                      SizedBox(width: 20.w,),
                      Text("取消",style: TextStyle(color: Colors.black),),
                    ]
                ),
                onTap: (){
                  Navigator.pop(context);
                },
              ),
              Text(widget.chooseTimeType==1? "装货时间":"卸货时间",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w600),),
              Row(
                children: [
                  GestureDetector(
                    child: Container(
                      width:50.w,
                      height:20.h,
                      decoration: BoxDecoration(
                          color: MyColors.themeColor,
                          borderRadius: BorderRadius.all(Radius.circular(20))),
                      child: Center(
                        child: Text("确认",style: TextStyle(color: Colors.white),),
                      ),
                    ),
                    onTap: (){
                      if(startTimeHour!=""&&startTimeDay!="")
                        Navigator.pop(context, [startTimeDay,startTimeHour,startTimeCode]);
                      else
                        BrnToast.show('请选择时间', context);
                    },
                  ),
                  SizedBox(width: 20.w,),
                ],
              ),
            ],
          ),
          SizedBox(height: 10.h,),
          Row(
            children: [
              Container(
                color: MyColors.backgreyColor,
                width: screenSize.width/3,
                height: 200.h,
                child:ListView.builder(
                  itemCount: dateList.length,
                  itemBuilder: (context, index) {
                    return Container(
                      padding: EdgeInsets.only(left: 8.w,top: 8.h,bottom: 8.h),
                      color: startTimeDay==dateList[index]?Colors.white:MyColors.backgreyColor,
                      child:
                      GestureDetector(
                        child:Text(
                          index==0?"今天"
                              :index==1?"明天"+"("+dateList[index]+")"
                              :index==2?"后天"+"("+dateList[index]+")"
                              :dateList[index]
                          ,style: TextStyle(color: startTimeDay==dateList[index]?MyColors.themeColor:Colors.black,fontSize: 14.sp),),
                        onTap: (){
                          setState(() {
                            startTimeDay=dateList[index];

                          });
                        },
                      ),

                    );
                  },
                ),
              ),
              Container(
                color: Colors.white,
                width: screenSize.width/2,
                height: 200.h,
                child:ListView.builder(
                  itemCount: chooseTimeList.length,
                  itemBuilder: (context, index) {
                    return Container(
                      padding: EdgeInsets.only(left: 8.w,top: 8.h,bottom: 8.h),
                      child:
                      GestureDetector(
                        child:Text(
                          chooseTimeList[index]
                          ,style: TextStyle(color: startTimeHour==chooseTimeList[index]?MyColors.themeColor:Colors.black,fontSize: 14.sp),),
                        onTap: (){
                          setState(() {
                            startTimeHour=chooseTimeList[index];
                            startTimeCode=timeCodeList[index];
                          });
                        },
                      ),

                    );
                  },
                ),
              ),
            ],
          )
        ],
      ),
    );
  }
  List<String> generateDateList() {
    List<String> dateList = [];
    DateTime today = DateTime.now();
    dateList.add(formatDate(today));

    for (int i = 1; i <= 5; i++) {
      DateTime nextDay = today.add(Duration(days: i));
      dateList.add(formatDate(nextDay));
    }

    return dateList;
  }

  String formatDate(DateTime date) {
    // 使用intl包中的DateFormat进行日期格式化
    return DateFormat('MM-dd').format(date);
  }
}

class WeightVelumSheet extends StatefulWidget {
  const WeightVelumSheet({super.key, required this.weight, required this.velum});
  final String weight;
  final String velum;
  @override
  State<WeightVelumSheet> createState() => _WeightVelumSheetState();
}

class _WeightVelumSheetState extends State<WeightVelumSheet> {
  String goodsWeight="";
  String goodsVelum="";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    goodsWeight=widget.weight;
    goodsVelum=widget.velum;
  }
  late TextEditingController _weightText = TextEditingController(text: widget.weight);
  late TextEditingController _velumtText = TextEditingController(text: widget.velum);
  @override
  Widget build(BuildContext context) {
    return Container(
      height:450.h,
      padding: EdgeInsets.only(top: 13.h,bottom: 44.h,left: 25.w,right: 16.w),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(10))),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              GestureDetector(
                child: Row(
                    children:[

                      Text("取消",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                    ]
                ),
                onTap: (){
                  Navigator.pop(context);
                },
              ),
              Row(
                children: [
                  Text("*",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp), ),
                  Text("总重量/体积",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w600),),
                  Text("（至少填写一项）",style: TextStyle(color: Colors.black,fontSize: 12.sp,fontWeight: FontWeight.w600),),
                ],
              ),

              Row(
                children: [
                  GestureDetector(
                    child: Container(
                      width:50.w,
                      height:20.h,
                      decoration: BoxDecoration(
                          color: MyColors.themeColor,
                          borderRadius: BorderRadius.all(Radius.circular(20))),
                      child: Center(
                        child: Text("确认",style: TextStyle(color: Colors.white,fontSize: 14.sp),),
                      ),
                    ),
                    onTap: (){
                      if(goodsWeight==""&&goodsVelum==""){
                        BrnToast.show(
                          "请至少填写一项",
                          context,
                          duration: BrnDuration.short,
                        );
                      }else{
                        Navigator.pop(context,[goodsWeight,goodsVelum]);
                      }

                    },
                  ),

                ],
              ),
            ],
          ),
          SizedBox(height: 34.h,),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text("重量（吨）",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
              Container(
                width: 200.w,
                height: 35.h,
                color: MyColors.backgreyColor,
                child:  TextField(
                  autofocus: true,
                  controller: _weightText,
                  decoration: InputDecoration(
                    hintText: '请输入货物重量',
                    hintStyle:TextStyle(fontSize: 13.sp,color: MyColors.hintColor),
                    filled: true,
                    fillColor: MyColors.backgreyColor,
                    border: InputBorder.none,
                    alignLabelWithHint: true,

                  ),
                  keyboardType: TextInputType.number,
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Colors.black,fontSize: 14.sp),
                  onChanged: (value) {
                    setState(() {
                      goodsWeight=value;
                    });
                  },
                ),
              ),
            ],
          ),
          SizedBox(height: 11.h,),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text("体积（方）",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
              Container(
                width: 200.w,
                height: 35.h,
                color: MyColors.backgreyColor,
                child:  TextField(
                  controller: _velumtText,
                  decoration: InputDecoration(
                    hintText:'请输入货物体积',
                    hintStyle:TextStyle(fontSize: 13.sp,color: MyColors.hintColor),
                    filled: true,
                    fillColor: MyColors.backgreyColor,
                    border: InputBorder.none,
                    alignLabelWithHint: true,

                  ),
                  keyboardType: TextInputType.number,
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Colors.black,fontSize: 14.sp),
                  onChanged: (value) {
                    setState(() {
                      goodsVelum=value;
                    });
                  },
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

class carLengthandTypeSheet extends StatefulWidget {
  const carLengthandTypeSheet({super.key, required this.carLength, required this.carType});
  final List carLength;
  final List carType;
  @override
  State<carLengthandTypeSheet> createState() => _carLengthandTypeSheetState();
}

class _carLengthandTypeSheetState extends State<carLengthandTypeSheet> {

  List<String> lengthList = [
    "1.8", "2.7", "3.8", "4.2", "5", "6.2", "6.8", "7.7", "8.2", "8.7", "9.6",
    "11.7", "12.5", "13", "13.7", "15", "16", "17.5"
  ];
  List<String> carTypeList = [
    "平板", "高栏", "厢式", "集装箱", "自卸", "冷藏", "保温",
    "高低板", "面包车", "棉被车", "爬梯车", "飞翼车", "依维柯"
  ];
  // List carLength=[];
  //
  // List carType=[];
  @override
  Widget build(BuildContext context) {
    return Container(
      height:550.h,
      padding: EdgeInsets.only(top: 15.h),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(10))),
      child: ListView(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              TextButton(onPressed: (){ Navigator.pop(context);}, child:  Text("取消       ",style: TextStyle(color: Colors.black,fontSize: 14.sp),)),

              Text("车长车型",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w600),),
              TextButton(onPressed: (){  if(widget.carType.length<4&&widget.carLength.length<4)
                Navigator.pop(context,[widget.carLength,widget.carType]);
              else
                BrnToast.show("最多选择3个车长、车型", context);}, child: Text("       确认",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),),
            ],
          ),
          SizedBox(height: 15.h,),
          Container(
            height: 34.h,
            color: Color.fromRGBO(251, 236, 228, 1),
            child: Center(
              child: Text("请根据实际货物运输需求合理选择车辆，避免超载超限",style: TextStyle(color: MyColors.themeColor,fontSize: 13.sp),
              ),
            ),
          ),
          SizedBox(height: 20.h,),
          Row(
            children: [
              SizedBox(width: 15.w,),
              Text("*",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
              Text("车长",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
              Text("（必填，最多3项）",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
            ],
          ),
          SizedBox(height: 8.h,),
          Center(
            // padding: const EdgeInsets.all(8.0),
            child: Wrap(
              spacing: 8.w, // 两个Container之间的水平间距
              runSpacing: 10, // 行与行之间的垂直间距
              children: lengthList.map((length) {
                bool? isSelected = widget.carLength.contains(length);
                return GestureDetector(
                  onTap: () {
                    // 处理点击事件
                    setState(() {
                      if (isSelected) {
                        // 如果已经被选中，则移除
                        widget.carLength.remove(length);
                      } else if (widget.carLength.length < 3) {
                        // 如果未被选中且未达到最大选择数量，则添加
                        widget. carLength.add(length);
                        print(widget.carLength);
                      }
                    });
                  },
                  child: Container(
                    width: 70.w, // Container宽度
                    height: 25.h, // Container高度，使其成为正方形
                    decoration: BoxDecoration(
                      color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                      borderRadius: BorderRadius.circular(3.0), // 设置Container的圆角
                    ),
                    child: Center(
                      child: Text(
                        length,
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                        ),
                      ),
                    ),
                  ),
                );
              }).toList(),
            ),
          ),



          SizedBox(height: 8.h,),
          Row(
            children: [
              SizedBox(width: 15.w,),
              Text("*",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
              Text("车型",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
              Text("（必填，最多3项）",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
            ],
          ),
          SizedBox(height: 8.h,),

          Center(
            // padding: const EdgeInsets.all(8.0),
            child: Wrap(
              spacing: 8.w, // 两个Container之间的水平间距
              runSpacing: 10, // 行与行之间的垂直间距
              children: carTypeList.map((length) {
                bool? isSelected = widget.carType.contains(length);

                return GestureDetector(
                  onTap: () {
                    // 处理点击事件
                    setState(() {
                      if (isSelected) {
                        // 如果已经被选中，则移除
                        widget.carType.remove(length);
                      } else if (widget.carType.length < 3) {
                        // 如果未被选中且未达到最大选择数量，则添加
                        widget.carType.add(length);
                        print(widget.carType);
                      }
                    });
                  },
                  child: Container(
                    width: 70.w, // Container宽度
                    height: 25.h, // Container高度，使其成为正方形
                    decoration: BoxDecoration(
                      color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                      borderRadius: BorderRadius.circular(3.0), // 设置Container的圆角
                    ),
                    child: Center(
                      child: Text(
                        length,
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                        ),
                      ),
                    ),
                  ),
                );
              }).toList(),
            ),
          ),

        ],
      ),
    );
  }
}